/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.dao.FinancialRecordDao;
import com.hboxs.asl.entity.FinancialRecord;
import com.hboxs.asl.entity.Member;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * Dao - 财务记录
 */
@Repository("financialRecordDaoImpl")
public class FinancialRecordDaoImpl extends BaseDaoImpl<FinancialRecord, Long> implements FinancialRecordDao {

    @Override
    public Page<FinancialRecord> incomeRecord(Pageable pageable, Member member) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<FinancialRecord> criteriaQuery = criteriaBuilder.createQuery(FinancialRecord.class);
        Root<FinancialRecord> root = criteriaQuery.from(FinancialRecord.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        if(member != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
        }
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), FinancialRecord.Status.incomeRecord));
        criteriaQuery.where(restrictions);
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createDate")));
        return super.findPage(criteriaQuery, pageable);
    }

    @Override
    public Page<FinancialRecord> expenditureRecord(Pageable pageable, Member member) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<FinancialRecord> criteriaQuery = criteriaBuilder.createQuery(FinancialRecord.class);
        Root<FinancialRecord> root = criteriaQuery.from(FinancialRecord.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        if(member != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
        }
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), FinancialRecord.Status.expenditureRecord));
        criteriaQuery.where(restrictions);
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createDate")));
        return super.findPage(criteriaQuery, pageable);
    }
}
